<template>
  <div id="rtuController" class="wrapper  h-100" style="overflow-x: auto">
    <div class="mb-3 d-flex align-items-center" style="min-width: 1560px">
      <div class="d-flex align-items-center">
        <!--<el-input placeholder="请输入内容"  class="input-with-select w300"  size="small" v-model="searchTxt">-->
          <!--<el-select class="w100" v-model="searchType" slot="prepend" placeholder="请选择">-->
            <!--<el-option label="控制箱" :value="1"></el-option>-->
            <!--<el-option label="RUT分组" :value="2"></el-option>-->
          <!--</el-select>-->
          <!--<el-button  slot="append"  class="ur-btn ur-btn-primary" @click="queryRtuInfo"><i class="iconfont icon-sousuo"></i>查询</el-button>-->
        <!--</el-input>-->

        责任区：
        <el-select class="w120 mr-2" v-model="rtu.regionId" slot="prepend" placeholder="请选择" size="small" @change="queryRtuInfo()">
          <el-option label="全部" :value="-1"></el-option>
          <el-option v-for="(item,index) in regions" :key="index" :label="item.Name" :value="item.Id"></el-option>
        </el-select>
        分组：
        <el-select class="w130 mr-2" v-model="rtu.groupId" slot="prepend" placeholder="请选择" size="small" @change="queryRtuInfo()">
          <el-option label="全部" :value="-1"></el-option>
          <el-option v-for="(item,index) in groups" :key="index" :label="item.GroupName" :value="item.Id"></el-option>
        </el-select>
        <el-input placeholder="请输入内容"  class="input-with-select w160"  size="small" v-model="rtu.value">
          <el-button v-if="limits.indexOf('2_06_01_01')!=-1" slot="append"  class="ur-btn ur-btn-primary" @click="queryRtuInfo()">查询</el-button>
        </el-input>
        <el-button v-if="limits.indexOf('2_06_01_02')!=-1" class="ur-btn ur-btn-primary ml-1" @click="lightOnOff('onOff')"><i class="iconfont icon-dankong"></i>开关灯</el-button>
        <el-button v-if="limits.indexOf('2_06_02_02')!=-1" class="ur-btn ur-btn-primary ml-1" @click="lightOnOff('dimming')"><i class="iconfont icon-dankong"></i>调光</el-button>
        <el-button v-if="limits.indexOf('2_06_01_04')!=-1" class="ur-btn ur-btn-primary ml-1" @click="clickFun(3)"><i class="iconfont icon-xiaoshi"></i>校时</el-button>
        <el-button v-if="limits.indexOf('2_06_01_06')!=-1" class="ur-btn ur-btn-primary ml-1" @click="clickFun(5)"><i class="iconfont icon-xiaoshi"></i>读取时钟</el-button>
        <!--<el-button class="ur-btn ur-btn-primary w75"><i class="iconfont icon-refresh-1-copy"></i>复位</el-button>-->
        <el-button v-if="limits.includes('2_06_01_05')" class="ur-btn ur-btn-primary ml-1" @click="clickFun(4)"><i class="iconfont icon-kaiguan"></i>重启</el-button>
        <el-button v-if="limits.includes('2_06_01_03')" type="warning" class="ur-btn ml-1" @click="clickFun(1)"><i class="iconfont icon-yijian"></i>一键全开</el-button>
        <el-button v-if="limits.includes('2_06_01_03')" type="warning" class="ur-btn ml-1" @click="clickFun(2)"><i class="iconfont icon-yijian"></i>一键全关</el-button>
        <el-button v-if="limits.includes('2_06_01_07')" type="success" class="ur-btn ml-1" @click="showSetOperatePwd=true"><i class="iconfont icon-shezhi"></i>一键全开关密码</el-button>
      </div>
      <ul class="result_group ml-auto">
        <li>下发总计：{{callNum.total}}</li>
        <li><i class="circle success"></i>成功：{{callNum.success}}</li>
        <li><i class="circle error"></i>失败：{{callNum.error}}</li>
      </ul>
    </div>
    <!--表格-->
    <el-table ref="rtuTable" :data="getGidData" style="min-width: 1560px" :height="clientHeight-212" highlight-current-row @selection-change="selsChange"  @row-click="rowClick">
      <el-table-column type="selection" width="50" align="center"></el-table-column>
      <el-table-column align="center" type="index" :index="indexMethod" label="序号" width="50"></el-table-column>
      <el-table-column v-for="(v,index) in tables.columns" :prop="v.field" :label="v.title" :width="v.width" align="center" :key="index">
        <template slot-scope="scope">
          <span v-if="v.field=='result'">
            <template v-if="scope.row[v.field]===1">
              <span v-if="scope.row.successInfo&&scope.row.successInfo!=''">
                {{scope.row.successInfo}}
              </span>
              <span v-else><i class='circle success'></i>成功</span>
            </template>
            <template v-else-if="scope.row[v.field]===0"><i class="circle error" ></i>失败</template>
            <template v-else>{{scope.row.result}}</template>
          </span>
          <span v-else>{{scope.row[v.field]}}</span>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <div style="min-width: 1560px;" class="mt-2 mb-1 d-flex justify-content-between align-items-center">
      <div class="" >
        <label>下发结果：</label>
        <div class="progress  w200 d-inline-block" style="height: 16px;vertical-align: middle">
          <div ref="progressBar" class="progress-bar progress-bar-striped" role="progressbar" style="width:0" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100"></div>
        </div>
      </div>
      <el-pagination class=" " @size-change="handleSizeChange" @current-change="handleCurrentChange" layout="total, sizes, prev, pager, next, jumper"
                     :page-sizes="[100,200,500,1000]" :current-page="currentPage" :page-size="pageSize" :total="total"></el-pagination>
    </div>

    <!--开关灯-->
    <el-dialog v-el-drag-dialog title="RTU控制" :visible.sync="showLoopOnOff" width="580px" top="15%" @click="showLoopOnOff=false">
      <div v-if="showLoopOnOff">
        <rtu-ctrl :boxs="sels" @updateResult="updateResult" @updateBar="updateBar"></rtu-ctrl>
      </div>
    </el-dialog>

    <!--调光-->
    <el-dialog v-el-drag-dialog title="RTU调光" :visible.sync="showdimming" width="370px" top="15%" @click="showdimming=false">
      <div v-if="showdimming">
        <rtu-dimming :boxs="sels" @updateResult="updateResult" @updateBar="updateBar" @close="showdimming=false"></rtu-dimming>
      </div>
    </el-dialog>

    <!--一键全开关:modal="false"-->
    <el-dialog v-el-drag-dialog :title="dialogTitle" :visible.sync="dialogAllOnOff" width="390px" top="20%">
      <div class="p-4" v-if="dialogAllOnOff">
        <div class="form-inline">
          <label>操作密码：</label>
          <el-tooltip class="item" :content="errors.first('pwd')" :value="errors.has('pwd')" :manual="true">
            <el-input type="password" size="small" class="w180" :class="{'is-error':errors.has('pwd')}" v-model="operatePwd" v-validate="'required'" name="pwd"></el-input>
          </el-tooltip>
          <el-button class="ur-btn w75 ml-3" :class="{'ur-btn-primary':!btnState}" type="info" @click="callFun" :disabled="btnState"><i class="iconfont icon-queding"></i>下发</el-button>
        </div>
        <!--<p class="text-danger mt-4">注：对所有设备进行控制</p>-->
      </div>
    </el-dialog>

    <!--一键全开关密码设置-->
    <el-dialog v-el-drag-dialog title="一键全开关密码设置" :visible.sync="showSetOperatePwd" width="460px" :center="true" top="15%">
      <template v-if="showSetOperatePwd">
        <edit-pwd :type="'operatePwd'" @closeEditPwd="closeEditPwd"></edit-pwd>
      </template>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
  import {mapState} from 'vuex'
  import api from 'api/api'
  import fetch from 'api/fetch'
  import rtuCtrl from './rtu-controller'
  import rtuDimming from './rtu-dimming'
  import elDragDialog from 'directive/el-dragDialog'
  import editPwd from 'base/editPwd/editPwd'

  export default {
    directives:{elDragDialog},
    components: {
      rtuCtrl,rtuDimming,editPwd
    },
    props: {},
    data() {
      return {
        total: 0,
        currentPage: 1,
        pageSize:100,
        searchType:1,
        searchTxt:'',
        tables: {
          sel: null,//选中行
          columns: [
            {field: "No", title: "控制箱编号", width: '120'},
            {field: "Manufacturer", title: "设备厂家", width: '140'},
            {field: "DevAddr", title: "设备地址", width: '160'},
            {field: "AreaName", title: "责任区", width: '140'},
            {field: "Location", title: "安装地点", width: null},
            {field: "opereaTime", title: "执行时间", width: '160'},
            {field: "result", title: "下发结果", width: null},
            {field: "resultInfo", title: "失败原因", width: null},
          ],
          data: []
        },
        sels:[],
        boxIds:[],
        showdimming:false,
        showLoopOnOff:false,
        dialogAllOnOff:false,
        dialogTitle:'',
        onOffStatus:0,//一键全开1 一键全关0
        operatePwd:'',
        callNum:{total:0,success:0,error:0},
        btnIndex:0,
        regions:[],
        groups:[],
        rtu:{regionId:-1,groupId:-1,value:''},
        showSetOperatePwd:false
      }
    },
    watch: {},
    computed: {
      getGidData(){
        if(this.tables.data.length){
          return this.tables.data.slice((this.currentPage-1)*this.pageSize,this.currentPage*this.pageSize)
        }
      },
      ...mapState({
        clientHeight:state=>state.comm.clientHeight,
        clientWidth:state=>state.comm.clientWidth,
        btnState:state=>state.user.btnState,
        limits:state=>state.user.userInfo.limits
      })
    },
    methods: {
      closeEditPwd(val){
        this.showSetOperatePwd=val
      },
      indexMethod(index) {
        return index + 1
      },
      rowClick(row, event, column){
      },
      handleSizeChange(val) {
        this.pageSize=val
        this.currentPage=1
      },
      handleCurrentChange(val) {
        this.currentPage=val
      },
      selsChange(sels) {
        this.boxIds=[]
        this.sels = sels
        sels.map(box=>{
          this.boxIds.push(box.BoxId)
        })
        this.sels.splice(0,0)
      },
      clickFun(v){
        this.btnIndex=v
        this.clearResult(this.boxIds,'start')
        this.onOffStatus=v==1?1:0//开关灯状态
        if(v==1||v==2){
          this.$confirm('确认'+(v==1?'一键全开':'一键全关')+'单灯？', '提示', {type: 'warning'})
            .then(() => {
              this.dialogAllOnOff=true
            }).catch(()=>{
          })
        }
        switch (v){
          case 1:
            this.$set(this.rtu,'groupId',-1)
            this.queryRtuInfo()
            return this.dialogTitle='一键全开'
          case 2:
            this.$set(this.rtu,'groupId',-1)
            this.queryRtuInfo()
            return this.dialogTitle='一键全关'
          case 3:
            this.dialogAllOnOff=true
            return this.dialogTitle='校时'
          case 4:
            this.dialogAllOnOff=true
            return this.dialogTitle='重启'
          case 5:
            this.dialogAllOnOff=true
            return this.dialogTitle='读取时钟'
        }
      },
      callFun() {
        let url = '', data = ''
        let callIndex = this.btnIndex
        let rows=[]
        let isOperate=false
        if (callIndex == 1 || callIndex == 2) {
          rows = this.tables.data

        } else {
          if (this.sels.length == 0) return this.$message.warning('未选择控制箱')
          rows = this.sels
        }
        this.$refs.progressBar.textContent = ''
        this.$refs.progressBar.style.width = 0
        this.$validator.validateAll().then((res) => {
          if (res) {
            this.$store.commit('user/SET_USER_PWD', this.operatePwd)
            this.$store.commit('user/SET_BTN_STATE', true)
            let pIndex = 1
            rows.map((box, index, arr) => {
              data = {boxDevAddr: box.DevAddr}
              if (callIndex == 1 || callIndex == 2) {//1一键全开 2一键全关
                url = '/Communication/Rtu/RtuAllController'
                data = {boxDevAddr: box.DevAddr, ctlType: this.onOffStatus}
              } else if (callIndex == 3) {//校时
                url = '/Communication/Rtu/RtuTiming'
              } else if (callIndex == 4) {//重启
                url = '/Communication/Rtu/RtuReboot'
              }else if (callIndex == 5) {//读取时钟
                url = '/Communication/Rtu/AFN0CF2'
                data = {devAddr: box.DevAddr}
              }
              api.fetchSimple(url, data)
                .then(r => {
                  //&&r.err.indexOf(box.Imei) != -1
                  box.opereaTime=api.formatDate(new Date(),'yyyy-MM-dd HH:mm:ss')
                  if (r.err) {
                    this.callNum.error++
                    box.result = 0
                    box.resultInfo = r.err
                  } else {
                    this.callNum.success++
                    box.result = 1
                    if(!api.isEmpty(r)&&callIndex==5){
                        box.successInfo = r.data['Time']
                    }else{
                      box.successInfo=''
                    }
                    box.resultInfo = '/'
                  }
                  let pcen = Math.round(pIndex / arr.length * 100) > 100 ? 100 : Math.round(pIndex / arr.length * 100)
                  this.updateBar(pcen)
                  pIndex++
                  if (pcen == 100) {
                    this.$store.commit('user/SET_BTN_STATE', false)
                    this.dialogAllOnOff = false
                    this.callNum.total = this.callNum.error + this.callNum.success
                    this.tables.data.splice(0, 0)
                    this.clearResult(this.boxIds,'end')
                  }
                })
            })
          }
        })
      },
      updateBar(pcen){//更新进度条宽度
        this.$refs.progressBar.style.width = pcen + '%'
        this.$refs.progressBar.textContent = pcen + '%'
      },
      scrollChange() {
        let _this=this
        var $scroll = this.$refs.rtuTable.$el.children[2]
        $scroll.onscroll = function (e) {
          let winPos = $scroll.scrollTop
          if (winPos == 0) {
            return false;
          } else {
            var num = Math.ceil(winPos / _this.trHeight)
            _this.startNum = num
          }
        }
      },
      queryRtuInfo(id){
        this.currentPage=1
        api.fetchSimple('/Manual/QueryRtuCtlInfo',this.rtu)
          .then(r => {
            if (!r.data) {
              return  // this.$message.success('未查询到数据')
            }
            this.total = r.data.length
            this.tables.data = r.data
            this.tables.data.map(v => {
              v['result'] = ''
              v['resultInfo'] = ''
              v['opereaTime'] = ''
            })
          })
      },
      lightOnOff(type){
        if (this.sels.length == 0) return this.$message({showClose:true,message:'勾选控制箱',type:'warning'})
        if(type=='onOff'){
          this.showLoopOnOff=true
        }else if(type=='dimming'){
          this.showdimming=true
        }
        this.clearResult(this.boxIds,'start')
      },
      updateResult(v) {
        this.callNum = v.callNum
        // this.tables.data.splice(0, 0)
        this.clearResult(v.boxIds,'end')
      },
      clearResult(boxIds,type){
        this.operatePwd=''
        this.$refs.rtuTable.clearSelection()
        this.tables.data.forEach(box => {
          let index=boxIds.indexOf(box.BoxId)
          if (index != -1) this.$refs.rtuTable.toggleRowSelection(box)
          if(type=='start'){//操作前清空结果
            this.callNum = {total: 0, success: 0, error: 0}
            this.$refs.progressBar.style.width =0
            this.$refs.progressBar.textContent =''
            box.result=''
            box.resultInfo = ''
            box.opereaTime = ''
          }
        })
      },
      queryRegion(){
        fetch.queryArea()
          .then(r=>{
            this.regions=r.data
          })
      },
      queryGroup(){
        this.groups=[]
        api.fetchSimple('/Group/QueryLikeRtu', { value:'' })
          .then(r=>{
            this.groups=r.data
            // r.data.map(r=>{
            //   if(r.Type==1){
            //     this.groups.push(r)
            //   }
            // })
          })
      }
    },
    created() {
      this.queryRegion()
      this.queryGroup()
      this.queryRtuInfo()
    },
    mounted() {
      this.scrollChange()
    }
  }
</script>
<style scoped lang="stylus" rel="stylesheet/stylus">
</style>
